package pure.engine.renderer 
{
	import pure.engine.system.ns_despair;
	
	use namespace ns_despair;
	
	// 渲染器管理器
		
	// [author] - Pure
	//
public class RendererManager 
{
	

	ns_despair static var m_rendererMap:Object = { };
	
	ns_despair static var numRenderer:int;
		
	ns_despair static var cachedCount:int;
	
	
	
	
   // 注册渲染器
	ns_despair static function register(R:Renderer):void
	{
		var ID:int;
		var group:Array;
		
		R.m_id             =  ID  =  ++cachedCount;
		m_rendererMap[ID]  =  R;
		numRenderer++;
	}	
	 
	
	// 注销渲染器
	ns_despair static function unregister(R:Renderer):Renderer 
	{	
		delete m_rendererMap[R.m_id];
		numRenderer--;
		return R;
	}
	
	
	// 更新渲染器
	
	// [-1]不可见， [0]画像不变，[1]画像变化，[2]范围变化
	ns_despair function update(elapsedT:Number):void
	{	
		var R:Renderer;
		var i:int, flag:int;
		var newRange:Number;
		
		// 碎片状态还原
		m_fragmentDirtyList[m_numRenderer] = 0;
		for (i = 0; i < m_numRenderer; i++) 
		{
			R     =  m_rendererList[i];
			flag  =  R.m_dirtyFlag;
			
			// 变为不可见
			if(flag == -1)
			{
				m_fragmentDirtyList[i] = flag;
				m_fragmentDirtyList[m_numRenderer] = i + 1;
				R.m_dirtyFlag = 0;
				return;
			}
			
			// 更新渲染器
			else if(R.m_visible)
			{	
				R.advance(elapsedT);
			}
			
			// 未变化
			if(flag == 0)  continue;
			
			// 碎片变化
			m_fragmentDirtyList[i] = flag;
			m_fragmentDirtyList[m_numRenderer] = i + 1;
			R.m_dirtyFlag = 0;
			
			if (flag == 2)  
			{
				m_rangeDirty = true;
			}
		}
		
		// 面积变化
		if(m_rangeDirty)
		{
			cachedArray.length = 0;
			for (i = 0; i < m_numRenderer; i++)
			{
				R = m_rendererList[i];
				if(R.m_visible)
				{
					cachedArray.push(R.m_oldRange);
				}
			}
			cachedArray.sort(Array.NUMERIC | Array.DESCENDING);
			
			newRange = cachedArray[0];
			if (newRange != m_range)
			{
				m_range            =  newRange;
				_worldRect.width   =  newRange * 2;
				_worldRect.height  =  newRange * 2;
			}
			m_rangeDirty = false;
		}
	}
}

}